package com.lzyyj.gmis.base.webui.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.lzyyj.common.BeanUtilsExt;
import com.lzyyj.gmis.base.model.IUser;
import com.lzyyj.gmis.base.webui.ICurrentUserAware;
import com.lzyyj.gmis.base.webui.action.LoginAction;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 授权检查拦截器，检查回话是否已进行身份验证，未验证的话转入登录页面，
 * 如果是Ajax请求，返回失败（暂未实现）
 * @author Lzyyj
 */
@SuppressWarnings("serial")
public class AuthorizationInterceptor extends AbstractInterceptor {

	private static final Log log = LogFactory
			.getLog(AuthorizationInterceptor.class);

	/**
	 * session 中当前用户 key
	 */
	private String currentUserKey = "CurrentUser";

	public String getCurrentUserKey() {
		return currentUserKey;
	}

	public void setCurrentUserKey(String currentUserKey) {
		this.currentUserKey = currentUserKey;
	}

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		Map<String, Object> session = ai.getInvocationContext().getSession();

		Object user = session.get(currentUserKey);

		// 对LoginAction,LogoutAction不做该项拦截

		Object action = ai.getAction();
		if (user == null) {
			if (!(action instanceof LoginAction)) {

				// 获取HttpServletRequest对象
				HttpServletRequest request = ServletActionContext.getRequest();

				// 获取此请求的地址，请求地址包含application name，进行subString操作，去除application
				// name
				String path = request.getRequestURI();
				String servletPath = request.getServletPath();
				String basePath = request.getContextPath();

				// 拼凑得到登陆之前的地址
				String realPath;

				// 获得请求中的参数
				String queryString = request.getQueryString();
				if (queryString == null) {
					realPath = servletPath;
				}else{
					realPath = servletPath + "?" + queryString;
				}
				
				// 存入session，方便调用
				session.put("prePage", realPath);
				
				log.info("未登录！");

				return Action.LOGIN;
			}
		} else {
			if (action instanceof ICurrentUserAware && user instanceof IUser) {
				BeanUtilsExt.setProperty(action, "currentUser", user);
			}
		}
		return ai.invoke();

	}
}